package edu.nf.supermarket.service.impl;

import edu.nf.supermarket.entity.ProductSpec;
import edu.nf.supermarket.entity.SpecAttributes;
import edu.nf.supermarket.mapper.ProductSpecMapper;
import edu.nf.supermarket.service.ProductSpecService;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @author gwf
 * @date 2025-06-18
 */
@Service("productSpec")
public class ProductSpecServiceImpl implements ProductSpecService {
    @Autowired
    private ProductSpecMapper productSpecMapper;

    @Override
    public List<ProductSpec> getProductSpecsByProductId(@Param("productId") Integer productId) {
        List<ProductSpec> productSpecs = productSpecMapper.getProductSpecsByProductId(productId);

        if (productSpecs == null || productSpecs.isEmpty()) {
            return new ArrayList<>();
        }

        // 将查询的结果按规格分组
        Map<Integer, ProductSpec> specMap = productSpecs.stream()
                .collect(Collectors.groupingBy(
                        ProductSpec::getSpecId,
                        Collectors.collectingAndThen(
                                Collectors.toList(),
                                list -> list.get(0)
                        )
                ));
        // 为每个规格设置属性列表
        specMap.values().forEach(spec -> {
           List<SpecAttributes> attributes = productSpecs.stream()
                   .filter(s -> s.getSpecId().equals(spec.getSpecId()))
                   .flatMap(s -> s.getAttributes() != null ? s.getAttributes().stream() : Stream.empty())
                   .distinct()
                   .collect(Collectors.toList());
           spec.setAttributes(attributes);
        });
        return new ArrayList<>(specMap.values());
    }

    @Override
    public List<ProductSpec> getAllActiveSpecs() {
        return productSpecMapper.getAllActiveSpecs();
    }

    @Override
    public ProductSpec getSpecById(@Param("specId") Integer specId) {
        return productSpecMapper.getSpecById(specId);
    }
}
